<template>
	<div class="my-content-layers flex-col" :class="{ scoped: !$store.chart.layers }">
		<div class="my-content-layers-top flex m-between">
			<div class="flex s-center">图层 <my-icon size="16" class="m-l-4" icon="Layers" /></div>
		</div>

		<el-empty v-if="reverseList.length === 0" :image-size="50">
			<template #description></template>
		</el-empty>

		<!-- 图层内容 -->
		<!-- https://github.com/SortableJS/vue.draggable.next -->
		<div class="my-content-layers-Draggable f1 h0 overflow-y-auto">
			<VueDraggableNext v-model="reverseList" ghostClass="ghost" @change="onMoveCallback">
				<template v-for="element in reverseList" :key="element.id">
					<div class="go-content-layer-box" @mousedown="boxMousedownHandle($event)">
						<!-- 组合 -->
						<layers-group-list-item v-if="element.isGroup" :componentGroupData="element" />
						<!-- 单组件 -->
						<layers-list-item v-else :componentData="element" />
					</div>
				</template>
			</VueDraggableNext>
		</div>
	</div>
</template>

<script setup>
import LayersListItem from './components/LayersListItem.vue';
import LayersGroupListItem from './components/LayersGroupListItem.vue';

// 逆序展示
const reverseList = computed({
	get: () => cloneDeep($store.chart.componentList.filter((item) => !item.parentId)).reverse(),
	set: function () {}
});

// 移动结束处理
function onMoveCallback(val) {
	const { oldIndex, newIndex } = val.moved;
	if (newIndex - oldIndex > 0) {
		// 从上往下
		const moveTarget = $store.chart.componentList.splice(-(oldIndex + 1), 1)[0];
		$store.chart.componentList.splice(-newIndex, 0, moveTarget);
	} else {
		// 从下往上
		const moveTarget = $store.chart.componentList.splice(-(oldIndex + 1), 1)[0];
		if (newIndex === 0) {
			$store.chart.componentList.push(moveTarget);
		} else {
			$store.chart.componentList.splice(-newIndex, 0, moveTarget);
		}
	}
}
function boxMousedownHandle(e) {
	const box = document.querySelector('.go-content-layer-box');
	if (e.target.contains(box)) {
		$store.chart.setTargetSelectChart();
	}
}
</script>

<style lang="scss" scoped>
$width: 200px;
@include b('content-layers') {
	width: $width;
	overflow: hidden;
	transition: all 0.4s;
	margin-right: 2px;
	background-color: var(--color-bg-2);
	&-top {
		width: $width;
		padding: 4px 8px;
		border-bottom: 2px solid var(--color-bg-1);
	}
	&-Draggable {
		width: $width;
	}
	&.scoped {
		width: 0;
		margin-right: 0;
	}
	.ghost {
		opacity: 0;
	}
	.go-layer-mode-active {
		color: #51d6a9;
	}
}
</style>
